// 1. 下包
// 2. 导入
import Vuex from 'vuex'
import Vue from 'vue'

// 3. 安装插件
Vue.use(Vuex)

// 4. 创建 store 对象
const store = new Vuex.Store({
  state: {
    list: JSON.parse(localStorage.getItem('todolist') || '[]'),
    isAll: false,
    isSel: 'all'
  },
  mutations: {
    // 删除
    delTask (state, id) {
      // 找到下标
      let index = state.list.findIndex(item => item.id == id)
      // 删除
      state.list.splice(index, 1)

      if (state.list.length == 0) return (state.isAll = false)
    },
    // 单选控制小选
    checkedBox (state, id) {
      // 找到下标
      let index = state.list.findIndex(item => item.id == id)

      // 取反赋值
      state.list[index].isDone = !state.list[index].isDone

      // 小选控制全选
      state.list.every(item => (state.isAll = item.isDone))
    },
    // 全选控制小选
    isAllCheckBox (state) {
      // 取反赋值
      state.isAll = !state.isAll

      if (state.isAll) {
        state.list.map(item => (item.isDone = true))
      } else {
        state.list.map(item => (item.isDone = false))
      }
    },
    // 添加数据
    addTask (state, payload) {
      let id =
        state.list.length > 0 ? state.list[state.list.length - 1].id + 1 : 100

      state.list.push({
        id,
        name: payload,
        isDone: false
      })
    },
    // isSel 状态
    changeIsSel (state, isSel) {
      state.isSel = isSel
    },
    // 清除已完成
    clearTask (state) {
      state.list = state.list.filter(item => !item.isDone)

      if (state.list.length == 0) return (state.isAll = false)
    }
  },
  getters: {
    // 数据切换
    showList (state) {
      if (state.isSel == 'yes') {
        return state.list.filter(item => item.isDone)
      } else if (state.isSel == 'no') {
        return state.list.filter(item => !item.isDone)
      } else {
        return state.list
      }
    }
  }
})

// 默认导出
export default store
